package cn.phantom.juctest;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.TestSemaphore")
public class TestSemaphore {
    public static void main(String[] args) {
        // 访问共享资源的线程上限
        Semaphore semaphore = new Semaphore(3);

        // 10个线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    log.debug("running...");
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("end.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }

            }, String.valueOf(i)).start();
        }

        /*
        19:08:00.026 c.TestSemaphore [1] - running...
        19:08:00.026 c.TestSemaphore [2] - running...
        19:08:00.026 c.TestSemaphore [0] - running...
        19:08:01.042 c.TestSemaphore [1] - end.
        19:08:01.042 c.TestSemaphore [2] - end.
        19:08:01.042 c.TestSemaphore [0] - end.
        19:08:01.042 c.TestSemaphore [5] - running...
        19:08:01.042 c.TestSemaphore [3] - running...
        19:08:01.042 c.TestSemaphore [4] - running...
        19:08:02.042 c.TestSemaphore [3] - end.
        19:08:02.042 c.TestSemaphore [5] - end.
        19:08:02.042 c.TestSemaphore [4] - end.
        19:08:02.042 c.TestSemaphore [6] - running...
        19:08:02.042 c.TestSemaphore [7] - running...
        19:08:02.042 c.TestSemaphore [8] - running...
        19:08:03.053 c.TestSemaphore [6] - end.
        19:08:03.053 c.TestSemaphore [7] - end.
        19:08:03.053 c.TestSemaphore [8] - end.
        19:08:03.053 c.TestSemaphore [9] - running...
        19:08:04.065 c.TestSemaphore [9] - end.
         */

    }
}
